//
//  WithdrawViewController.m
//  HengYouCai
//
//  Created by lwj on 2017/11/17.
//  Copyright © 2017年 lwj. All rights reserved.
//

#import "WithdrawViewController.h"
#import "PswInputView.h"
#import "GetBackPasswordVC.h"
#import "HengYouCai-Swift.h"
@interface WithdrawViewController ()<UITextFieldDelegate>
//体现至银行卡
@property (weak, nonatomic) IBOutlet UILabel *topLabel;
//账户余额
@property (weak, nonatomic) IBOutlet UILabel *balanceLabel;
//体现金额
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
//实际到账
@property (weak, nonatomic) IBOutlet UILabel *amount2Label;

/**
 提现金额限制提示信息
 */
@property (weak, nonatomic) IBOutlet UILabel *limitLab;

/**
 提现金额输入框
 */
@property (weak, nonatomic) IBOutlet UITextField *moneyTF;

/**
 确定按钮
 */
@property (weak, nonatomic) IBOutlet UIButton *certainBtn;

/**
 提现描述
 */
@property (weak, nonatomic) IBOutlet UILabel *detailLab;

/**
 银行卡信息等
 */
@property (nonatomic, strong)NSDictionary *totalDic;

/**
 账户余额
 */
@property (weak, nonatomic) IBOutlet UILabel *availableMoneyLab;

/**
 实际到账金额
 */
@property (weak, nonatomic) IBOutlet UILabel *finalMoneyLab;

/**
 bankStatus（处理银行维护公告(有值就公告)及提现按钮状态(0启用1停用)）
 */
@property(nonatomic, strong) NSString * btnStatus;

@end

@implementation WithdrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self UIInit];
    [self statNetworking];
    [self rac_single];
    
}

/**
 界面初始化
 */
- (void)UIInit
{
    // 处理系统的调整偏移
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight(), 0, 0, 0);
//    self.title = @"提现";
    self.view.backgroundColor = Normal_BackColor;
    self.moneyTF.delegate = self;
    
}

/**
 监听输入框 和 确定按钮
 */
- (void)rac_single
{
    /**
     监听金额输入框 控制按钮是否可使用
     */
    WLGetWeakSelf(weakSelf, self);
    
    [self.moneyTF.rac_textSignal subscribeNext:^(NSString * _Nullable x) {
        //停用
        if ([weakSelf.btnStatus isEqualToString:@"1"]) {
            weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
            weakSelf.certainBtn.enabled = NO;
            return;
        }
        double money = [x doubleValue];
        if (_totalDic) {
            if (money>0) {
                weakSelf.certainBtn.backgroundColor = Normal_RedColor;
                weakSelf.certainBtn.enabled = YES;
            }else{
                weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
                weakSelf.certainBtn.enabled = NO;
            }
        }else{
            
            weakSelf.certainBtn.backgroundColor = Normal_UnselecBtnColor;
            weakSelf.certainBtn.enabled = NO;
        }
        
    }];
    
    
    //MARK:确认提现
    [[self.certainBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        
        // 最少提现100元
        double money = weakSelf.moneyTF.text.doubleValue;
        if (money < 100) {
            [weakSelf.view showHUDWarnTips:@"最少提现100元" hideDelay:1];
            return ;
        }
        
        // 判断提现金额是否大于账户余额
        if (weakSelf.availableMoneyLab.text.length>1) {
            double accountMoney = 0;
            accountMoney = [[weakSelf.availableMoneyLab.text substringToIndex:weakSelf.availableMoneyLab.text.length - 1] doubleValue];
            if (money > accountMoney) {
                [weakSelf.view showHUDWarnTips:@"提现金额超过账户可用余额!" hideDelay:kHUDHideDelay];
                return ;
            }
        }
        /**
         显示密码框
         */
        [PswInputView initWithFrame:CGRectMake(0, 0, f_Device_w, f_Device_h) money:[NSString stringWithFormat:@"提现￥%@",[NSString stringWithFormat:@"%.2f",weakSelf.moneyTF.text.floatValue]] psdBlock:^(NSString *str, PswInputView *pswView) {
            
            /**
             获取到密码
             */
            [HYCNetService withdrawWithdrawSubWithDict:@{@"amount":weakSelf.moneyTF.text,@"payPwd":str} onSuccess:^(NSDictionary *dictResult) {
                //提现成功
                [self.view hideHUDLoading:0];
                WithdrowFinishVC *withdrowFinish = [[WithdrowFinishVC alloc] init];
                withdrowFinish.moneyText = [NSString stringWithFormat:@"%@元",dictResult[@"withdrawAmount"]];
                withdrowFinish.bankText = [NSString stringWithFormat:@"%@(%@)",weakSelf.totalDic[@"bankName"],weakSelf.totalDic[@"bankCode"]];
                withdrowFinish.tips = dictResult[@"tips"];
                [pswView removeFromSuperview];
                [weakSelf.navigationController pushViewController: withdrowFinish animated:YES];
                
            } andFailed:^(NSInteger code, NSString *errorMsg) {
                [self.view hideHUDLoading:0];
                
                if(code == 401){
                    // 回到登录界面 移除密码框
                    [pswView removeFromSuperview];
                }else {
                    // 清空密码小黑点
                    pswView.errorMessageLab.text = errorMsg;
                    
                    UIImageView *img1 = [pswView viewWithTag:10001];
                    UIImageView *img2 = [pswView viewWithTag:10002];
                    UIImageView *img3 = [pswView viewWithTag:10003];
                    UIImageView *img4 = [pswView viewWithTag:10004];
                    UIImageView *img5 = [pswView viewWithTag:10005];
                    UIImageView *img6 = [pswView viewWithTag:10006];
                    
                    img1.hidden = YES;
                    img2.hidden = YES;
                    img3.hidden = YES;
                    img4.hidden = YES;
                    img5.hidden = YES;
                    img6.hidden = YES;
                    // 错误提示文字做动画
                    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
                    animation.values = @[
                                         [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position],
                                         [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x-20, pswView.errorMessageLab.layer.position.y)],
                                         [NSValue valueWithCGPoint:CGPointMake(pswView.errorMessageLab.layer.position.x+20, pswView.errorMessageLab.layer.position.y)],
                                         [NSValue valueWithCGPoint:pswView.errorMessageLab.layer.position]
                                         ];
                    animation.keyTimes = @[
                                           @(0),@(0.3),@(0.7),@(1)
                                           ];
                    animation.autoreverses = NO;
                    animation.duration = 0.5;
                    [pswView.errorMessageLab.layer addAnimation:animation forKey:@"anmi"];
                    
                }
                
            }];
            
            
        } forgetPsd:^{
            
            /**
             忘记密码
             */
            GetBackPasswordVC *change = [[UIStoryboard storyboardWithName:@"Profile" bundle:nil] instantiateViewControllerWithIdentifier:@"GetBackPasswordVCID"];
            [self.navigationController pushViewController:change animated:YES withHideBottomBarWhenPush:YES pop:YES];
        }];
        
    }];
}
#pragma tableviewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
#pragma tableviewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WithdrawCellID"];
    if (_totalDic) {
        UIImageView *bankIcon = [cell viewWithTag:1001];
        UILabel *bankLab = [cell viewWithTag:1002];
        UILabel *kahaoLab = [cell viewWithTag:1003];
        bankLab.text = _totalDic[@"bankName"];
        kahaoLab.text = [NSString stringWithFormat:@"**** **** **** %@",_totalDic[@"bankCode"]==nil?@"" :_totalDic[@"bankCode"] ];
        [bankIcon sd_setImageWithURL:[NSURL URLWithString:_totalDic[@"bankImageUrl"]]];
    }
    
    return cell;
}

//MARK:UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSRange rangeItem = [textField.text rangeOfString:@"."];
    //判断字符串是否包含"."
    if (rangeItem.location != NSNotFound){
        if ([string isEqualToString:@"."]) {
            return NO;
        }else{
            //rangeItem.location == 0 说明“.”在第一个位置
            if (range.location>rangeItem.location+2) {
                return NO;
            }
        }
    }else{
        if ([string isEqualToString:@"."]) {
            if (textField.text.length<1) {
                textField.text = @"0.";
                return NO;
            }
            return YES;
        }
        // 最多输入11位
        if (range.location>10) {
            return NO;
        }
    }
    
    return YES;
}
//监听完成事件 处理实际到账金额展示
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    //判断提现金额是否大于账户余额
    double money = self.moneyTF.text.doubleValue;
    double accountMoney = 0;
    accountMoney = [[self.availableMoneyLab.text substringToIndex:self.availableMoneyLab.text.length - 1] doubleValue];
    if (textField.text.length&&!(money > accountMoney)) {//不为空
        [HYCNetService withdrawActualAmtWithDict:@{@"amount":textField.text} OnSuccess:^(NSDictionary *dictResult) {
            [self.view hideHUDLoading:0];
            
            self.finalMoneyLab.text = [NSString stringWithFormat:@"%@元",dictResult[@"withdrawAmount"]];
        } andFailed:^(NSInteger code, NSString *errorMsg) {
            [self.view showHUDFailTips:errorMsg hideDelay:kHUDHideDelay];
            self.finalMoneyLab.text = @"0.00元";
        }];
    }else{
        [self.view hideHUDLoading:0];
        self.finalMoneyLab.text = @"0.00元";
    }
}

/**
 数据源字典
 */
- (NSDictionary *)totalDic
{
    if (!_totalDic) {
        _totalDic = [NSDictionary dictionary];
    }
    return _totalDic;
}
/**
 网络请求
 */
- (void)statNetworking
{
    [self.tableView showHUDLoading];
    WLGetWeakSelf(weakSelf, self);
    
    [HYCNetService withdrawWithdrawInitWithOnSuccess:^(NSDictionary *dictResult) {
        //
        weakSelf.totalDic = dictResult;
        self.topLabel.text = dictResult[@"bankLabel"];
        self.balanceLabel.text = dictResult[@"balanceLabel"];
        self.amountLabel.text = dictResult[@"amountLabel"];
        self.amount2Label.text = dictResult[@"amount2Label"];
        [self.certainBtn setTitle:dictResult[@"buttonLabel"] forState:UIControlStateNormal];
        self.title = dictResult[@"title"];
        
        
        _limitLab.text = dictResult[@"withdrawTips"];
        _moneyTF.placeholder = [NSString stringWithFormat:@"%@",dictResult[@"amountTips"]];
        _availableMoneyLab.text = [NSString stringWithFormat:@"%@元",dictResult[@"availableMoney"]];
        _detailLab.text = dictResult[@"tips"];
        
        [self handleWarnWithStatus:dictResult[@"bankStatus"] warnStr:dictResult[@"bankTips"]];
        
        [weakSelf.tableView hideHUDLoading:0];
        [weakSelf.tableView reloadData];
    } andFailed:^(NSInteger code, NSString *errorMsg) {
        //
        [weakSelf.tableView reloadData];
        [weakSelf.tableView showHUDFailTips:errorMsg hideDelay:1];
    }];
    
}

//bankTips  --String 类型    获取银行卡维护日志 ，若在维护中，则返回内容，否则返回 "" bankStatus
/**  处理银行维护公告(有值就公告)及提现按钮状态(0启用1停用) */
- (void)handleWarnWithStatus:(NSString *)statusStr warnStr:(NSString *)warnStr{
    self.btnStatus = statusStr;
    if (warnStr.length) {//公告有
        [self.tableView addSubview:[self getWarnNoticeView:warnStr]];
        [UIView animateWithDuration:0.618 animations:^{
            self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight()+23, 0, 0, 0);
        }];
    }else{
        [[self.tableView viewWithTag:100] removeFromSuperview];
        self.tableView.contentInset = UIEdgeInsetsMake(kJcwGetNavHeight(), 0, 0, 0);
    }
    //非1启用
    
    self.certainBtn.userInteractionEnabled = ![statusStr isEqualToString:@"1"];
    
}
//获取公告视图
- (UIView *)getWarnNoticeView:(NSString *)warnStr{
    UIView * temp = [[UIView alloc] initWithFrame:CGRectMake(0, -23, f_Device_w, 23)];
    temp.tag = 100;
    temp.backgroundColor = UIColorFromRGB(0xffe8bd);
    
    UIImageView * image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bank_inform"]];
    image.frame = CGRectMake(15, 5.25, 12.5, 12.5);
    [temp addSubview:image];
    
    UILabel * lab = [[UILabel alloc] initWithFrame:CGRectMake(32.5, 0, f_Device_w-32.5, 23)];
    lab.text = warnStr;
    lab.font = [UIFont systemFontOfSize:12];
    lab.textColor = Normal_RedColor;
    [temp addSubview:lab];
    return temp;
}

@end

